<?php
    function run_cmd($cmd){
        // build command
        $command = str_replace("%program%", ABAVC_FFMPEG_PATH , ABAVC_FFMPEG_COMMANDLINE);
        $command = str_replace("%input%", "\"{$file_path}\"" , $command);
        $command = str_replace("%output%", "\"{$des}\"" , $command);

        $command = escapeshellcmd ($command);
        $ret=exec($command, $ret2);

        // chmod
        chmod($des, 0775);

    }
    function database_connect($host,$user,$pass,$name)
    {
        global $db;
        $db = mysql_connect($host,$user,$pass);
        mysql_select_db($name,$db);
    }

    function exponent_unhtmlentities( $str )
    {
        $trans = get_html_translation_table(HTML_ENTITIES);
        $trans['&apos;'] = '\'';
        $trans=array_flip($trans);

        $trans['&apos;'] = '\'';
        $trans['&#039;'] = '\'';
        return strtr($str, $trans);
    }

    function tar_bz2_file($dir_from,$dir_to)
    {
        $command='tar cjfv '.$dir_to.'.tar.bz2 '.$dir_from;
        $command = escapeshellcmd ($command);
        $ret=exec($command, $ret2); 
    }
    function scan_virus($dir='.')
    {
        $command='clamdscan --fdpass --stdout  '.$dir;
        $command = escapeshellcmd ($command);
        $ret=exec($command, $ret2); 
        echo "\r\n";
        $log='';
        $have_virus=false;
        $backup_dir_virus='';
        $count=0;
        foreach($ret2 as $file)
        {
            if(strpos($file, 'FOUND')>0)
            {
                $count++;
                $file=substr($file,0,strpos($file,': '));
                $file_tmp=explode('/',$file);
                $filename=end($file_tmp);
                //Move file
                $time=date('Y-m-d');
                $backup_dir_virus=BASE.'auto_backup/virus/'.$time;
                if(!is_dir($backup_dir_virus))
                    mkdir($backup_dir_virus);
                $new_name='Virus_scan_result_'.$filename.'_'.md5(time().$file);
                $log.=$file.'<br>-Virus name: '.$filename.'<br>-Rename to: '.$new_name.'<br>-File size:'.number_format(filesize($file) / 1024, 2) . ' KB<br><br>';
                copy($file,$backup_dir_virus.'/'.$new_name);
                unlink($file);
                $have_virus=true;
            }
        }
        echo "Scan complete ".end($ret2)."\r\n";

        if($have_virus)
        {
            tar_file($backup_dir_virus,BASE.'auto_backup/virus/virus_'.$time);
            if(AUTO_CLEAR)
            {
                deleteDirectory($backup_dir_virus);
            }
            print("Begin upload virus\r\n");
            $file_info=uploadto_ggdrive(BASE.'auto_backup/virus/virus_'.$time.'.tar','Virus_');
            print("Upload virus complete\r\n");
            $content='['.date('Y-m-d H:i:s').']<br>Found virus when scanning system<br>Here is the list of all virus:<br>'.$log.'<br>Total: '.$count.' virus<br>All virus have been packed to :'.$file_info->link.'<br>Scan '.end($ret2);
            sendmail('Found virus when scanning system', $content);
        }
        else
        {
            echo "Not found virus! \r\n";
        }
        return $ret;
    }
    function tar_file($dir_from,$dir_to)
    {
        $command='tar cf '.$dir_to.'.tar '.$dir_from.'/';
        $command = escapeshellcmd ($command);
        $ret=exec($command, $ret2); 
        if(AUTO_CLEAR)
        {
            deleteDirectory($dir_from);
        }
    }
    
    /**
    * Split file into serveral parts
    * 
    * @param mixed $file File path
    * @param mixed $mb How many MB (number)
    */
    function split_file($file, $mb)
    {
        //split -b 300m "newlarge.tgz" "newlarge.tgz.part-"
        $command='split -d -b '.$mb.'m "'.$file.'" "'.$file.'.part-"';
        $command = escapeshellcmd ($command);
        $ret=exec($command, $ret2); 
    }
    
    function backup_tables($host,$user,$pass,$name,$tables = '*')
    {
        global $db;
        $result=null;
        mysql_query('SET NAMES utf8');
        mysql_query('SET CHARACTER SET utf8');
        //mysql_set_charset('utf8',$db);
        //get all of the tables
        if($tables == '*')
        {
            $tables = array();
            $result = mysql_query('SHOW TABLES');
            while($row = mysql_fetch_row($result))
            {
                $tables[] = $row[0];
            }
        }
        else
        {
            $tables = is_array($tables) ? $tables : explode(',',$tables);
        }

        //cycle through
        $return="";
        foreach($tables as $table)
        {
            $result = mysql_query('SELECT * FROM '.$table);
            $num_fields = mysql_num_fields($result);
            $return.= 'DROP TABLE '.$table.';';
            $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
            $return.= "\n\n".$row2[1].";\n\n";

            for ($i = 0; $i < $num_fields; $i++) 
            {
                while($row = mysql_fetch_row($result))
                {
                    $return.= 'INSERT INTO '.$table.' VALUES(';
                    for($j=0; $j<$num_fields; $j++) 
                    {
                        $row[$j] = addslashes($row[$j]);
                        //$row[$j] = ereg_replace("\n","\\n",$row[$j]);
                        $row[$j] = preg_replace("/\n/","\\n",$row[$j]);
                        if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                        if ($j<($num_fields-1)) { $return.= ','; }
                    }
                    $return.= ");\n";
                }
            }
            $return.="\n\n\n";
        }
        $dir=BASE.'auto_backup/backup/'.date('Y-m-d').'/db.sql';
        //save file
        /*$handle = fopen($dir,'w+');
        fwrite($handle,$return);
        fclose($handle);*/
        $gzdata = gzencode($return, 9);
        $handle = fopen($dir.'.gz','w+');
        fwrite($handle, $gzdata);
        fclose($handle);
        return $dir;
    }
    //Mail
    function sendmail($subject, $content)
    {
        require_once(BASE.'subsystems/mail.php');
        $mail= new exponentMail();
        $list_mail=explode(',',MAIL_TO);
        $content=$content.'<br><hr>'.SIGNATURE;
        $sending=$mail->real_send($subject, $content, 0, $list_mail,true,MAIL_FROM,MAIL_FROM_NAME);
        echo "Mail result:". $sending ."\r\n";
        //If can't send mail by exponent, send by PHP
        if(!$sending&&(SMTP_USE_PHP_MAIL==1))
        {
            $headers  = 'MIME-Version: 1.0' . "\r\n";
            $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
            $headers .= 'To: '.MAIL_TO. "\r\n";
            $headers .= 'From: '.MAIL_FROM_NAME.' <'.MAIL_FROM.'>' . "\r\n";
            $php_send=mail(MAIL_TO, $subject, $content, $headers);
        }
        if($sending||$php_send)
        {
            echo "Send mail success!\r\n";
        }
        else
        {
            echo "Send mail failure!\r\n";    
        }
    }
    //Delete folder function
    function deleteDirectory($dir) {
        if (!file_exists($dir)) return true;
        if (!is_dir($dir) || is_link($dir)) return unlink($dir);
        foreach (scandir($dir) as $item) {
            if ($item == '.' || $item == '..') continue;
            if (!deleteDirectory($dir . "/" . $item)) {
                chmod($dir . "/" . $item, 0777);
                if (!deleteDirectory($dir . "/" . $item)) return false;
            };
        }
        return rmdir($dir);
    }
    function clear_backup($dir,$leave_files)
    {
        foreach( glob("$dir/*") as $file ) {
        if( !in_array(basename($file), $leave_files) )
        unlink($file);
        }
    }
?>
